package com.scs.application.modules.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.scs.application.core.consts.Const;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.FileUtils;
import com.scs.application.core.utils.UtilCommon;
import com.scs.application.modules.sys.dto.StringReceive;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.service.InitDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/program/initData")
@Slf4j
public class InitDataController {

    @Autowired
    InitDataService initDataService;

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public RestResult getList() {
        return RestResult.ok("获取初始化SQL数据成功！", initDataService.getList());
    }

    @RequestMapping(value = "/execute", method = RequestMethod.POST)
    public RestResult execute(String fileName) {
        initDataService.execute(fileName);
        return RestResult.ok("执行SQL数据成功，" + UtilCommon.getStr(fileName, "全部"));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public RestResult save(@RequestBody StringReceive entity) {
        initDataService.save(entity.getContents());
        return RestResult.ok("保存初始化数据成功！");
    }

    /**
     * @Description： 保存sql
     */
    @PostMapping(value = "/saveSql", produces = "application/json; charset=utf-8")
    public RestResult saveSql(@RequestBody Map<String, String> reqData) {
        String fileName = reqData.get("fileName");
        String sql = reqData.get("sql");
        File file = new File(Const.INIT_DATE_SRC + fileName + ".txt");
        try {
            FileUtils.writeStringToFile(file, sql, "utf-8");
        } catch (IOException e) {
            log.error("InitDataController.saveSql.error", e);
            return RestResult.error("保存失败，表名：" + fileName + "，原因：" + e.getMessage());
        }
        return RestResult.ok("保存成功，表名：" + fileName);
    }

    /**
     * @Description： 获取sql
     */
    @GetMapping(value = "/getSql")
    public RestResult getSql(String fileName) throws IOException {
        List<String> lines = FileUtils.readFileLinesStore("init-data/" + fileName + ".txt");
        return RestResult.ok("获取成功", lines);
    }

    /**
     * @Description： 拆分 init-data-sql.json，仅第一次
     */
    @RequestMapping(value = "/splitAll", method = RequestMethod.GET)
    public RestResult splitAll() throws Exception {
        String protocol = Const.class.getClassLoader().getResource("").getProtocol();
        if (protocol.startsWith("jar")) {
            throw new BusinessException("jar包方式启动不支持拆分，请在开发环境操作");
        }

        JSONObject sqlStore = JSONObject.parseObject(FileUtils.readFileStore(Const.getInitDataSqlSrc()));
        JSONArray items = sqlStore.getJSONArray("items");

        String fileName = "";
        boolean isEdit = false;
        int numAll = 0, numAdd = 0;
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            String tables = item.getString("tables");
            String sql = item.getString("sql");
            fileName = Const.INIT_DATE_SRC + tables + ".txt";
            File file = new File(fileName);
            numAll++;
            if (file.exists()) {
                continue;
            }
            file.createNewFile();
            FileUtils.writeStringToFile(file, sql, "utf-8");
            items.getJSONObject(i).remove("sql");
            isEdit = true;
            numAdd++;
        }

        if (isEdit) {
            sqlStore.put("items", items);
            FileUtils.writeTxtFile(Const.INIT_DATA_SQL_SRC, JSON.toJSONString(sqlStore, SerializerFeature.PrettyFormat));
        }
        return RestResult.ok("init-data-sql.json拆分完成 记录数量：" + numAll + "，新拆分文件数量：" + numAdd);
    }
}
